package com.ktv.web.controller.com.ktv.web.handler.impl;

import com.ktv.web.controller.com.ktv.web.handler.RequestHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;

/**
 * Created by ivey.yuan on 2016/3/2.
 */
public abstract class AbstractRequestHandler implements RequestHandler {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    public AsyncContext startAsyncRequest(HttpServletRequest request, HttpServletResponse response) {

        if (!request.isAsyncSupported()) {
            throw new IllegalStateException("Async request not support!,please check your web.xml or tomcat");
        }
        AsyncContext asyncContext = request.isAsyncStarted() ? request.getAsyncContext() : request.startAsync();
        asyncContext.setTimeout(1 * 30 * 1000);
        asyncContext.addListener(new AsyncListener() {
            @Override
            public void onComplete(AsyncEvent event) throws IOException {
                System.out.println("Request completed ");
            }

            @Override
            public void onTimeout(AsyncEvent event) throws IOException {
                logger.info("Request timeout  reconnected ");
                event.getAsyncContext().dispatch();
            }

            @Override
            public void onError(AsyncEvent event) throws IOException {
                logger.error("error", event.getThrowable());
                event.getAsyncContext().complete();
            }

            @Override
            public void onStartAsync(AsyncEvent event) throws IOException {
            }
        });
        return asyncContext;
    }

    protected void writerResponse(HttpServletResponse response, String body,String contentType) throws IOException {
        response.setContentType(contentType);
        response.addHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
        response.setHeader("Cache-Control", "pre-check=0,post-check=0");
        response.setDateHeader("Expires", 0);
        response.getWriter().write(body);
        response.flushBuffer();
    }
}
